<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('修改论文')" />
    <th:block th:include="include :: datetimepicker-css" />
    <th:block th:include="include :: bootstrap-fileinput-css"/>
    <th:block th:include="include :: select2-css"/>
    <style>
        .row-top-margin {
            margin-top: 20px;
            clear: both;
        }
        .first-author-aligned .first-author-label {
            width: 25% !important;
        }
        .first-author-aligned .first-author-input {
            width: 66.66% !important;
            padding-right: 15px !important; /* 与Bootstrap的col-sm-8保持一致 */
        }
    </style>
</head>
<body class="white-bg">
    <div class="wrapper wrapper-content animated fadeInRight ibox-content">
        <form class="form-horizontal m" id="form-paper-edit" th:object="${sciPaperA}">
            <input name="id" id="p_id" th:field="*{id}" type="hidden">

            <div class="form-group">
                <label class="col-sm-3 control-label">论文名称：</label>
                <div class="col-sm-8">
                    <input name="paperTitle" th:field="*{paperTitle}" class="form-control" type="text">
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">论文类型：</label>
                <div class="col-sm-8">
                    <select name="paperType" class="form-control" th:with="type=${@dict.getType('sci_paper_type')}" required>
                        <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}" th:field="*{paperType}"></option>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">论文类别：</label>
                <div class="col-sm-8">
                    <select name="paperCategory" class="form-control" th:with="type=${@dict.getType('sci_paper_k')}" required>
                        <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}" th:field="*{paperCategory}"></option>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">发表期刊：</label>
                <div class="col-sm-8">
                    <input name="publishedJournal" th:field="*{publishedJournal}" class="form-control" type="text">
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">发表时间：</label>
              <div class="col-sm-8">
                <div class="input-group date">
                    <input autocomplete="off" name="publicationTime" th:field="*{publicationTime}"
                           th:value="${#dates.format(publicationTime, 'yyyy-MM-dd')}"  class="form-control"
                           placeholder="yyyy-MM-dd" type="text">
                    <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                </div>
              </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">是否与行业联合发表：</label>

                <div class="col-sm-9" >
                    <label class="radio-box">
                        <input name="isIndustryCollaborative" th:field="*{isIndustryCollaborative}" class="form-control" type="radio" value="是">是</label>
                    <label class="radio-box">
                        <input name="isIndustryCollaborative" th:field="*{isIndustryCollaborative}" class="form-control" type="radio" value="否">否</label>
                </div>

<!--                <div class="col-sm-8">-->
<!--                    <input name="isIndustryCollaborative" th:field="*{isIndustryCollaborative}" class="form-control" type="text">-->
<!--                </div>-->

            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">是否与地方联合发表：</label>
                <div class="col-sm-9" >
                    <label class="radio-box">
                        <input name="isLocalCollaborative" th:field="*{isLocalCollaborative}" class="form-control" type="radio" value="是">是</label>
                    <label class="radio-box">
                        <input name="isLocalCollaborative" th:field="*{isLocalCollaborative}"class="form-control" type="radio" value="否">否</label>
                </div>
<!--                <div class="col-sm-8">-->
<!--                    <input name="isLocalCollaborative" th:field="*{isLocalCollaborative}" class="form-control" type="text">-->
<!--                </div>-->

            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">是否与国际联合发表：</label>
                <div class="col-sm-9" >
                    <label class="radio-box">
                        <input name="isInternationalCollaborative" th:field="*{isInternationalCollaborative}" class="form-control" type="radio" value="是">是</label>
                    <label class="radio-box">
                        <input name="isInternationalCollaborative" th:field="*{isInternationalCollaborative}"class="form-control" type="radio" value="否">否</label>
                </div>
<!--                <div class="col-sm-8">-->
<!--                    <input name="isInternationalCollaborative" th:field="*{isInternationalCollaborative}" class="form-control" type="text">-->
<!--                </div>-->
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">是否是跨学科论文：</label>
                <div class="col-sm-9" >
                    <label class="radio-box">
                        <input name="isCrossDiscipline" th:field="*{isCrossDiscipline}" class="form-control" type="radio" value="是">是</label>
                    <label class="radio-box">
                        <input name="isCrossDiscipline" th:field="*{isCrossDiscipline}"class="form-control" type="radio" value="否">否</label>
                </div>
<!--                <div class="col-sm-8">-->
<!--                    <input name="isCrossDiscipline" th:field="*{isCrossDiscipline}" class="form-control" type="text">-->
<!--                </div>-->
            </div>
            <div class="col-md-12">
                <div class="form-group">
                    <label class="col-sm-3 control-label">是否是独立作者：</label>
                    <div class="col-sm-9" id = "isIndependentauthor">
                        <label class="radio-box">
                            <input name="isIndependentauthor" th:field="*{isIndependentauthor}" class="form-control" type="radio" value="1" required>是</label>
                        <label class="radio-box">
                            <input name="isIndependentauthor" th:field="*{isIndependentauthor}" class="form-control" type="radio" value="0">否</label>
                    </div>
                </div>
            </div>
<!--            <div class="col-md-6">-->
<!--                <div class="form-group">-->
<!--                    <label class="col-sm-3 control-label">排名：</label>-->
<!--                    <div class="col-sm-8" th:with="type=${@dict.getType('sci_paper_qwer')}">-->
<!--                        <select th:field="*{paperRanking}" disabled class="form-control m-b">-->
<!--                            &lt;!&ndash; 默认选项 &ndash;&gt;-->
<!--                            <option value="" th:if="${#lists.isEmpty(type)}">无可用选项</option>-->
<!--                            &lt;!&ndash; 动态生成选项 &ndash;&gt;-->
<!--                            <option th:each="dict : ${type}"-->
<!--                                    th:text="${dict.dictLabel}"-->
<!--                                    th:value="${dict.dictValue}"-->
<!--                                    th:selected="${sciPaperA.paperRanking == dict.dictValue}">-->
<!--                            </option>-->
<!--                        </select>-->
<!--                    </div>-->
<!--                </div>-->
<!--            </div>-->
<!--          <div class="form-group">-->
<!--            <label class="col-sm-3 control-label">排名：</label>-->
<!--            <div class="col-sm-8">-->
<!--              <select id="paperRanking"  name="paperRanking" class="form-control m-b" th:with="type=${@dict.getType('sci_paper_qwer')}" required>-->
<!--                <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}"></option>-->
<!--              </select>-->
<!--            </div>-->
<!--          </div>-->
            <div class="col-xs-6" id="firstAuthorGroup">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required first-author-label">一作：</label>
                    <div class="col-sm-8 first-author-input">
                        <select name="firstPersonId" class="form-control m-b" id="firstPersonId">
                            <option value="">---请选择--</option>
                            <option th:each="user : ${sysUsers}"
                                    th:text="${user.userName}"
                                    th:value="${user.userId}"
                                    th:selected="${sciPaperA.firstPersonId == user.userId.toString()}"
                                    th:data-user-id="${user.userId}"></option>
                        </select>
                    </div>
                </div>
            </div>

            <div class="col-xs-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">二作：</label>
                    <div class="col-sm-8">
                        <select name="secondPersonId" class="form-control m-b" id="secondPersonId">
                            <option value="">---请选择--</option>
                            <option th:each="user : ${sysUsers}"
                                    th:text="${user.userName}"
                                    th:value="${user.userId}"
                                    th:selected="${sciPaperA.secondPersonId == user.userId.toString()}"
                                    th:data-user-id="${user.userId}"></option>
                        </select>
                    </div>
                </div>
            </div>

            <div class="col-xs-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">三作：</label>
                    <div class="col-sm-8">
                        <select name="thirdPersonId" class="form-control m-b" id="thirdPersonId">
                            <option value="">---请选择--</option>
                            <option th:each="user : ${sysUsers}"
                                    th:text="${user.userName}"
                                    th:value="${user.userId}"
                                    th:selected="${sciPaperA.thirdPersonId == user.userId.toString()}"
                                    th:data-user-id="${user.userId}"></option>
                        </select>
                    </div>
                </div>
            </div>

            <div class="col-xs-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">四作：</label>
                    <div class="col-sm-8">
                        <select name="fourthPersonId" class="form-control m-b" id="fourthPersonId">
                            <option value="">--请选择--</option>
                            <option th:each="user : ${sysUsers}"
                                    th:text="${user.userName}"
                                    th:value="${user.userId}"
                                    th:selected="${sciPaperA.fourthPersonId == user.userId.toString()}"
                                    th:data-user-id="${user.userId}"></option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="col-xs-10">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">通讯作者：</label>
                    <div class="col-sm-8">
                        <select name="communicationAuthorId" class="form-control m-b" id="correspondingAuthorId">
                            <option value="">--请选择--</option>
                        </select>
                    </div>
                </div>
            </div>

            <div class="form-group" id="searchWebGroup">
                <label class="col-sm-3 control-label">论文网址：</label>
                <div class="col-sm-8">
                    <input name="search_web" th:field="*{search_web}"class="form-control" type="text">
                </div>
            </div>
          <div class="form-group">
            <label class="col-sm-3 control-label">备注：</label>
            <div class="col-sm-8">
              <input name="remarks" th:field="*{remarks}" class="form-control" type="text">
            </div>
          </div>
          <div class="form-group">
            <label class="col-sm-3 control-label">论文收录通知：</label>
            <div class="col-sm-8">
              <input type="hidden" name="text_paper">
              <div class="file-loading">
                <input class="form-control file-upload" id="text_paper" name ="file" type="file" >
              </div>
            </div>
          </div>
          <div class="form-group">
            <label class="col-sm-3 control-label">论文原文：</label>
            <div class="col-sm-8">
              <input type="hidden" name="word_paper">
              <div class="file-loading">
                <input class="form-control file-wupload" id="word_paper" name ="file" type="file" >
              </div>
            </div>
          </div>

            <h4 class="form-header h4 tdiv2"  style="display:none;">批阅记录</h4>
            <div class="row tdiv2" style="display:none;">
                <div class="col-sm-12">

                    <div class="form-group"  >
                        <table id='bootstrap-table'></table>
                    </div>
                </div>
            </div>

        </form>
    </div>
    <div class="row">
        <div class="col-sm-offset-5 col-sm-10">
            <button type="button" class="btn btn-sm btn-primary" onclick="submitHandler()">  </i>保 存</button>&nbsp;
            <button type="button" class="btn btn-sm btn-danger" onclick="closeItem()"> 关 闭 </button>
        </div>
    </div>

    <th:block th:include="include :: footer" />
    <th:block th:include="include :: datetimepicker-js" />
    <th:block th:include="include :: bootstrap-fileinput-js"/>
    <th:block th:include="include :: select2-js"/>
    <script th:inline="javascript">

        function displayFileName(inputId, fileNameId) {
            const input = document.getElementById(inputId);
            const fileNameSpan = document.getElementById(fileNameId);
            if (input.value) {
                const fileName = input.value.split('/').pop(); // 获取文件名
                const parts = fileName.split('_'); // 按下划线分割
                const firstPart = parts[0]; // 下划线前的部分

                const dotParts = fileName.split('.'); // 按点分割
                const lastPart = dotParts[dotParts.length - 1]; // 点后的部分
                const year =0;
                fileNameSpan.textContent = `${firstPart}.${lastPart}`; // 组合并显示
            } else {
                fileNameSpan.textContent = '';
            }
        }
        function downloadFile(type){
            var contextPath = '/' + window.location.pathname.split('/')[1];
            var c = window.location.origin + contextPath + $("#"+type).val();
            if(c){
                var a = document.createElement("a");
                a.href=c;
                a.download="";
                a.style.display = "none";
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
            }else{
                alert("网址无效");
            }
        }

        // function chakanpaper(){
        //     var c = $("#text_paper").val();
        //     console.log("c:",c)
        //     $.modal.openTab("查看论文文件" ,c);
        // }



        var prefix = ctx + "system/paper";
        $("#form-paper-edit").validate({
            focusCleanup: true
        });
        // 当被退回后进行更新时显示退回记录
        $(function(){
            var pid = $("#p_id").val();
            var options = {
                url: prefix + "/bhxs/"+pid,
                showSearch: false,
                showRefresh: false,
                showToggle: false,
                showColumns: false,
                pagination:false,
                columns: [

                    {
                        field : 'create_time',
                        title : '批阅时间',
                        width: 200

                    } ,
                    {
                        field : 'uname',
                        title : '批阅人',
                        width: 100
                    },
                    {
                        field : 'concate',
                        title : '内容',
                        width: 500
                    },
                    {
                        field : 'state',
                        title : '审核状态',
                        width: 100
                    } ]
            };
            $.table.init(options);

            $('#bootstrap-table').on('load-success.bs.table', function (e, name, args) {
                console.log('Event Name:', name.rows);
                var a =$("#state").val();

                if(a != 1){
                    if(name.rows.length > 0){
                        $(".tdiv2").show();
                    }
                }

            });
        })

        function submitHandler() {
            if ($.validate.form()) {
                // 校验作者信息是否重复
                const authorIds = [
                    $("#firstPersonId").val(),
                    $("#secondPersonId").val(),
                    $("#thirdPersonId").val(),
                    $("#fourthPersonId").val()
                ].filter(id => id !== ""); // 过滤掉空值

                // 检查是否有重复的作者ID
                const uniqueAuthors = new Set(authorIds);
                if (authorIds.length !== uniqueAuthors.size) {
                    $.modal.alertError("第一作者到第四作者不能重复");
                    return false;
                }
                if ($("#correspondingAuthorId").val() == null || $("#correspondingAuthorId").val() == ""){
                    if ($("#isIndependentauthor").val() == "0"){
                        $.modal.alertError("通讯作者不能为空");
                        return false;
                    }
                }
                // 校验网址
                const searchWeb = $("input[name='search_web']").val().trim();
                if (searchWeb !== "" && !validateUrl(searchWeb)) {
                    $.modal.alertError("论文网址格式不正确，请以 http:// 或 https:// 开头");
                    return false;
                }
                
                $.operate.saveTab(prefix + "/edit", $('#form-paper-edit').serialize());
            }
        }
        
        // 更新通讯作者下拉框选项
        function updateCorrespondingAuthorOptions() {
            const correspondingAuthorSelect = $('#correspondingAuthorId');
            const selectedAuthors = [];
            
            // 获取所有选中的作者ID和名称
            $('#firstPersonId, #secondPersonId, #thirdPersonId, #fourthPersonId').each(function() {
                const authorId = $(this).val();
                const authorName = $(this).find('option:selected').text();
                if (authorId && authorId !== '') {
                    selectedAuthors.push({
                        id: authorId,
                        name: authorName
                    });
                }
            });
            
            // 保存当前选中的通讯作者
            const currentSelected = correspondingAuthorSelect.val();
            
            // 清空下拉框
            correspondingAuthorSelect.empty();
            correspondingAuthorSelect.append('<option value="">--请选择--</option>');
            
            // 添加选中的作者作为选项
            selectedAuthors.forEach(function(author) {
                correspondingAuthorSelect.append('<option value="' + author.id + '">' + author.name + '</option>');
            });
            
            // 如果之前选中的通讯作者仍然在选项中，则保持选中状态
            if (currentSelected && selectedAuthors.some(author => author.id === currentSelected)) {
                correspondingAuthorSelect.val(currentSelected);
            }
        }
        
        function validateUrl(string) {
            // 确保网址以 http:// 或 https:// 开头
            if (!string.startsWith('http://') && !string.startsWith('https://')) {
                return false;
            }

            // 使用正则表达式验证网址格式
            const urlPattern = /^(https?):\/\/([^\s\.]+\.[^\s]{2,}|www\.[^\s]+\.[^\s]{2,})/;
            return urlPattern.test(string);
        }
        $(".file-wupload").each(function (i) {
            var val = $("input[name='" + this.id + "']").val()
            $(this).fileinput({
                'uploadUrl': ctx + 'common/upload/lw',
                initialPreviewAsData: true,
                initialPreview: [val],
                maxFileCount: 1,
        maxFileSize: 51200,
                autoReplace: true,
                allowedFileExtensions: ["doc","docx"]
            }).on('fileuploaded', function (event, data, previewId, index) {
                $("input[name='" + event.currentTarget.id + "']").val(data.response.url)
            }).on('fileremoved', function (event, id, index) {
                $("input[name='" + event.currentTarget.id + "']").val('')
            })
            $(this).fileinput('_initFileActions');
        });
        $(".file-upload").each(function (i) {
            var val = $("input[name='" + this.id + "']").val()
            $(this).fileinput({
                'uploadUrl': ctx + 'common/upload/lw',
                initialPreviewAsData: true,
                initialPreview: [val],
                maxFileCount: 1,
        maxFileSize: 51200,
                autoReplace: true,
                allowedFileExtensions: ["pdf"]
            }).on('fileuploaded', function (event, data, previewId, index) {
                $("input[name='" + event.currentTarget.id + "']").val(data.response.url)
            }).on('fileremoved', function (event, id, index) {
                $("input[name='" + event.currentTarget.id + "']").val('')
            })
            $(this).fileinput('_initFileActions');
        });

        $("input[name='publicationTime']").datetimepicker({
            format: "yyyy-mm-dd",
            minView: "month",
            autoclose: true
        });

        $(document).ready(function() {
            // 初始化选择器为select2，提供搜索能力
            $('#firstPersonId, #secondPersonId, #thirdPersonId, #fourthPersonId, #correspondingAuthorId').select2({
                width: '100%',
                placeholder: '\u002D\u002D请选择\u002D\u002D',
                allowClear: true
            });

            // 初始化通讯作者下拉框（在页面加载时）
            updateCorrespondingAuthorOptions();

            // 设置默认选中的通讯作者
            var communicationAuthorId = /*[[${sciPaperA.communicationAuthorId}]]*/ '';
            if (communicationAuthorId && communicationAuthorId !== '') {
                $('#correspondingAuthorId').val(communicationAuthorId).trigger('change');
            }

            // 根据论文类别，应用启禁用规则
            const initialCategory = $('select[name="paperCategory"]').val();
            if (initialCategory) {
                applyAuthorEnableRule(initialCategory);
            }

            // 监听1-4作的选择变化
            $('#firstPersonId, #secondPersonId, #thirdPersonId, #fourthPersonId').on('change', function() {
                updateCorrespondingAuthorOptions();
            });

            // 监听论文类别变化，动态启禁用作者下拉框
            $('select[name="paperCategory"]').on('change', function () {
                applyAuthorEnableRule($(this).val());
            });
            
            // 监听是否独立作者变化
            $('input[name="isIndependentauthor"]').on('change', function () {
                handleIndependentAuthor($(this).val());
            });
            
            // 页面加载时检查是否独立作者
            const isIndependent = $('input[name="isIndependentauthor"]:checked').val();
            if (isIndependent === "1") {
                handleIndependentAuthor("1");
            }
        });

        function applyAuthorEnableRule(inputValue){
            // 如果选择的是独立作者，优先应用独立作者逻辑
            const isIndependent = $('input[name="isIndependentauthor"]:checked').val();
            if (isIndependent === "1") {
                handleIndependentAuthor("1");
                return;
            }
            
            // 10,11,12: 只允许1-2作者
            if(inputValue == "10" || inputValue == "11" || inputValue == "12") {
                $('#secondPersonId').prop('disabled', false);
                $('#thirdPersonId, #fourthPersonId').prop('disabled', true).val('').trigger('change');
            } else if (inputValue == "8" || inputValue == "9"){
                // 8,9: 仅第一作者
                $('#secondPersonId, #thirdPersonId, #fourthPersonId').prop('disabled', true).val('').trigger('change');
            } else {
                // 其他: 全部可选
                $('#secondPersonId, #thirdPersonId, #fourthPersonId').prop('disabled', false);
            }
            // 更新通讯作者选项
            updateCorrespondingAuthorOptions();
        }
        
        function handleIndependentAuthor(value) {
            if (value === "1") {
                // 是独立作者：清除二三四作者和通讯作者，隐藏相应控件
                $('#secondPersonId, #thirdPersonId, #fourthPersonId, #correspondingAuthorId').val('').trigger('change');
                $('.form-group:has(#secondPersonId), .form-group:has(#thirdPersonId), .form-group:has(#fourthPersonId), .form-group:has(#correspondingAuthorId)').hide();
                
                // 调整一作布局使其与其他控件对齐
                $('#firstAuthorGroup').removeClass('col-xs-6').addClass('first-author-full-width');
                $('#firstAuthorGroup .form-group').addClass('first-author-aligned');
                
                // 移动论文网址到下一行显示
                $('#searchWebGroup').addClass('row-top-margin');
            } else {
                // 不是独立作者：显示所有作者控件，恢复布局
                $('.form-group:has(#secondPersonId), .form-group:has(#thirdPersonId), .form-group:has(#fourthPersonId), .form-group:has(#correspondingAuthorId)').show();
                
                // 恢复一作原始布局
                $('#firstAuthorGroup').removeClass('first-author-full-width').addClass('col-xs-6');
                $('#firstAuthorGroup .form-group').removeClass('first-author-aligned');
                
                // 恢复论文网址到原始位置
                $('#searchWebGroup').removeClass('row-top-margin');
            }
            updateCorrespondingAuthorOptions();
        }
        
        function handleIndependentAuthor(value) {
            if (value === "1") {
                // 是独立作者：清除二三四作者和通讯作者，隐藏相应控件
                $('#secondPersonId, #thirdPersonId, #fourthPersonId, #correspondingAuthorId').val('').trigger('change');
                $('.form-group:has(#secondPersonId), .form-group:has(#thirdPersonId), .form-group:has(#fourthPersonId), .form-group:has(#correspondingAuthorId)').hide();
                
                // 调整一作布局使其与其他控件对齐
                $('#firstAuthorGroup').removeClass('col-xs-6').addClass('first-author-full-width');
                $('#firstAuthorGroup .form-group').addClass('first-author-aligned');
                
                // 移动论文网址到下一行显示
                $('#searchWebGroup').addClass('row-top-margin');
            } else {
                // 不是独立作者：显示所有作者控件，恢复布局
                $('.form-group:has(#secondPersonId), .form-group:has(#thirdPersonId), .form-group:has(#fourthPersonId), .form-group:has(#correspondingAuthorId)').show();
                
                // 恢复一作原始布局
                $('#firstAuthorGroup').removeClass('first-author-full-width').addClass('col-xs-6');
                $('#firstAuthorGroup .form-group').removeClass('first-author-aligned');
                
                // 恢复论文网址到原始位置
                $('#searchWebGroup').removeClass('row-top-margin');
            }
            updateCorrespondingAuthorOptions();
        }

        // window.onload = function() {
        //     displayFileName('text_paper', 'contractFileName');
        //     displayFileName('word_paper', 'wordFileName');
        // };
    </script>
</body>
</html>
